<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/03/22
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\user;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;
use ImiApp\ApiServer\Api\Model\GoodsskuPrice;

use Imi\Cache\CacheManager as Cache;

/**
 * 拍卖👏
 * @Auth(name="token",nologin={"get_coupons_list","get_coupons_data","index4"})
 * @Controller("/user.auction3/")
 */
class Auction3 extends AuctionBean
{
    protected $noNeedLogin = ['no'];
    protected $noNeedRight = ['*'];



    // /**
    //  * 获取拍卖首页4种商品
    //  * @param string $status 2=预展示,3=进行中
    //  * @return void
    //  * @Action
    //  */
    // public function index4($status = '2')
    // {
    //     if (!$status)
    //         $status = '2';
    //     $whereCom['apply_status'] = '2'; //申请状态:1=待审核,2=通过,3=拒绝
    //     // $type_status = 拍卖类型:1=贝壳竞拍,2=降价拍,3=升价拍,4=暗拍(降价拍),5=暗拍(升价拍)
    //     $type_status1 = Db::name('auction')->where('type_status', '=', '1')->where('status', '=', $status)->whereEx($whereCom)->orderRaw('end_time asc,id desc')->limit(2)->select()->getArray();
    //     if ($type_status1) {
    //         foreach ($type_status1 as &$val) {
    //             $temp = $this->get_field_arr($val, ['id', 'type_status', 'goods_id']);
    //             $val = $temp;
    //             $val['goods'] = $this->GetGoodsShortDataById3($val['goods_id']);
    //         }
    //     }
    //     $list['type_status1'] = $type_status1;


    //     $type_status2 = Db::name('auction')->where('type_status', '=', '2')->where('status', '=', $status)->whereEx($whereCom)->orderRaw('end_time asc,id desc')->limit(2)->select()->getArray();
    //     if ($type_status2) {
    //         foreach ($type_status2 as &$val) {
    //             $temp = $this->get_field_arr($val, ['id', 'type_status', 'goods_id']);
    //             $val = $temp;
    //             $val['goods'] = $this->GetGoodsShortDataById3($val['goods_id']);
    //         }
    //     }
    //     $list['type_status2'] = $type_status2;


    //     $type_status3 = Db::name('auction')->where('type_status', '=', '3')->where('status', '=', $status)->whereEx($whereCom)->orderRaw('end_time asc,id desc')->limit(2)->select()->getArray();
    //     if ($type_status3) {
    //         foreach ($type_status3 as &$val) {
    //             $temp = $this->get_field_arr($val, ['id', 'type_status', 'goods_id']);
    //             $val = $temp;
    //             $val['goods'] = $this->GetGoodsShortDataById3($val['goods_id']);
    //         }
    //     }
    //     $list['type_status3'] = $type_status3;


    //     $type_status4 = Db::name('auction')->where('type_status', '=', '4')->where('status', '=', $status)->whereEx($whereCom)->orderRaw('end_time asc,id desc')->limit(1)->select()->getArray();
    //     if ($type_status4) {
    //         foreach ($type_status4 as &$val) {
    //             $temp = $this->get_field_arr($val, ['id', 'type_status', 'goods_id']);
    //             $val = $temp;
    //             $val['goods'] = $this->GetGoodsShortDataById4($val['goods_id']);
    //         }
    //     }
    //     $list['type_status4'] = $type_status4;


    //     $type_status5 = Db::name('auction')->where('type_status', '=', '5')->where('status', '=', $status)->whereEx($whereCom)->orderRaw('end_time asc,id desc')->limit(1)->select()->getArray();
    //     if ($type_status5) {
    //         foreach ($type_status5 as &$val) {
    //             $temp = $this->get_field_arr($val, ['id', 'type_status', 'goods_id']);
    //             $val = $temp;
    //             $val['goods'] = $this->GetGoodsShortDataById5($val['goods_id']);
    //         }
    //     }
    //     $list['type_status5'] = $type_status5;

    //     return $this->success($status, $list);
    // }

    // /**
    //  * 获取拍卖列表
    //  *
    //  * @param integer $page 页1
    //  * @param integer $limit 数量10
    //  * @param string $search 搜索
    //  * @param string $type_status 拍卖类型:1=贝壳竞拍,2=降价拍,3=升价拍,4=暗拍(降价拍),5=暗拍(升价拍)
    //  * @param int $goodscate_id 商品分类:1=精选,2=上新,3=推荐
    //  * @param string $status 状态:2=预展示,3=进行中
    //  * @return void
    //  * @Action
    //  */
    // public function get_auction_list(?int $page = 1, ?int $limit = 10, $apply_status = null, $search = null, $type = null, $status = null, $type_status = null,?int $goodscate_id = null)
    // {

    //     $page = $page ?: 1;
    //     $limit = $limit ?: 10;

    //     $where['apply_status'] = '2';
    //     $orderRaw = 'end_time asc';

    //     if ($goodscate_id){
    //         if($goodscate_id<4){
    //             switch ($goodscate_id) {
    //                 case '1':
    //                     $orderRaw = 'end_time asc';
    //                     break;
    //                 case '2':
    //                     $orderRaw = 'id asc';
    //                     break;
    //                 case '2':
    //                     $orderRaw = 'end_time asc';
    //                     break;
    //                 default:
    //                     $orderRaw = 'end_time asc';
    //                     break;
    //             }

    //         }else{
    //             $where['goodscate_id'] = $goodscate_id;
    //         }

    //     }




    //     if ($search)
    //         $where['title'] = ['like', '%' . $search . '%'];

    //     $status = $status ?: '2';
    //     $where['status'] = $status;
    //     if ($type_status)
    //         $where['type_status'] = $type_status;

    //     $list = Db::name('auction')

    //         // ->whereEx($this->whereCom)

    //         ->whereEx($where)
    //         ->whereIsNull('deletetime')
    //         ->orderRaw($orderRaw)
    //         ->page($page, $limit)
    //         ->select()
    //         ->getArray();
    //     if ($list) {
    //         foreach ($list as $key => &$val) {
    //             $val = $this->ChangeFieldList($val);
    //         }
    //     }
    //     return $this->success('', $list);
    // }


    // /**
    //  * 详情页
    //  *
    //  * @param int $id 拍卖id
    //  * @return void
    //  * @Action
    //  */
    // public function get_auction_data($id){
    //     $auction = $this->getAuctionData($id);
    //     if (!$auction) {
    //         return $this->error('没有该活动', $id, CODE_拍卖活动不存在);
    //     }

    //     switch ($auction['type_status']) {
    //         case '1':
    //             $拍卖类型 = '贝壳竞拍';
    //             if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_贝壳竞拍)) {
    //                 return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
    //             }
    //             break;
    //         case '2':
    //             $拍卖类型 = '降价拍';
    //             if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_降价拍)) {
    //                 return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
    //             }
    //             break;
    //         case '3':
    //             $拍卖类型 = '升价拍';
    //             if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_升价拍)) {
    //                 return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
    //             }
    //             break;
    //         case '4':
    //             $拍卖类型 = '暗拍(降价拍)';
    //             if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_暗拍_降)) {
    //                 return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
    //             }
    //             break;
    //         case '5':
    //             $拍卖类型 = '暗拍(升价拍)';
    //             if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_暗拍_升)) {
    //                 return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
    //             }
    //             break;
    //         default:
    //             # code...
    //             break;
    //     }

    //     $auction = $this->ChangeFieldData($auction);
    //     return $this->success('ok',$auction);
    // }



    /**
     * 报名
     *
     * @param int $id 拍卖id
     * @return void
     * @Action
     */
    public function enroll($id)
    {
        $auction = $this->getAuctionData($id);
        if (!$auction) {
            return $this->error('没有该拍卖', '', CODE_拍卖活动不存在);
        }
        $user_id = $this->auth->user()->id;
        if ($auction['type_status'] != '3') {
            return $this->error('接口错误');
        }

        switch ($auction['type_status']) {
            case '1':
                $拍卖类型 = '贝壳竞拍';
                if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_贝壳竞拍)) {
                    return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
                }
                break;
            case '2':
                $拍卖类型 = '降价拍';
                if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_降价拍)) {
                    return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
                }
                break;
            case '3':
                $拍卖类型 = '升价拍';
                if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_升价拍)) {
                    return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
                }
                break;
            case '4':
                $拍卖类型 = '暗拍(降价拍)';
                if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_暗拍_降)) {
                    return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
                }
                break;
            case '5':
                $拍卖类型 = '暗拍(升价拍)';
                if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_暗拍_升)) {
                    return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
                }
                break;
            default:
                # code...
                break;
        }



        if ($auction['apply_status'] != '2') {
            return $this->error('该拍卖未通过', '', CODE_该拍卖未通过);
        }

        if ($auction['status'] == '1') {
            return $this->error('还未展示', '', CODE_该拍卖不能报名);
        }

        if ($auction['status'] == '3') {
            return $this->error('已经开拍', '', CODE_该拍卖不能报名);
        }

        //status` enum('1','2','3','5','6') DEFAULT '1' COMMENT '状态:1=待展示,2=预展示,3=进行中,5=结束,6=已下架',
        if ($auction['status'] == '2') {

            //第一次报名用户减少库存
            $data2['auction_id'] = $id;
            $_报名_ = Db::name('auction_enroll')->whereEx($data2)->find();
            if (!$_报名_) {
                // $goods_sku_price_arr = explode(',', $auction['goods_sku_price_ids']);
                // //            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!如果库存没有了,就不能进行了
                // foreach ($goods_sku_price_arr as $key => $sku_id) {
                //     $this->DecGoodsStock($sku_id, 1, '报名' . $拍卖类型 . '活动减少库存', $id);
                // }

                $this->冻结拍卖全部库存($auction, '报名' . $拍卖类型 . '活动减少库存');
            }

            //判断有没有报名过
            $data['user_id'] = $this->auth->user()->id;
            $data['auction_id'] = $id;
            $res = Db::name('auction_enroll')->whereEx($data)->find();
            if ($res) {
                return $this->error('您已报名该拍卖活动了', '', CODE_您已报名该拍卖活动);
            }




            //扣除积分
            if ($this->auth->score() < $auction['enroll_score']) {
                // return $this->error('报名积分不足', $auction['enroll_score'], CODE_积分不足);

                $data['score'] = 0;
                $data['return_status'] = '2'; //状态:1=未退积分,2=已退
            } else {
                $this->DecUserScore($this->auth->user()->id, (float)$auction['enroll_score'], '报名' . $拍卖类型, 20, $id);
                $this->IncUserFreeze($this->auth->user()->id, 'score', (float)$auction['enroll_score'], 'auction_enroll', $id, '报名' . $拍卖类型, $auction['id'], null, $auction['id']);
                //加入报名
                $data['score'] = $auction['enroll_score'];
                $data['return_status'] = '1'; //状态:1=未退积分,2=已退

            }

            $data['time'] = time();


            Db::name('auction_enroll')->insert($data);
            $_报名状态缓存_ = 'auction_enroll_' . (string)$id . '_user_id' . (string)$user_id;
            Cache::set('redis', $_报名状态缓存_, true);

            //判断开始人数
            if ($auction['start_status'] == 'number') {
                //获取报名总人数
                $count = Db::name('auction_enroll')->where('auction_id', '=', $id)->count();
                if ($count >= $auction['enroll_num']) {
                    //开始拍卖活动
                    var_dump('升价拍-人数-报名已满', $count);
                    //修改状态              //状态:1=待展示,2=预展示,3=进行中,5=完成结束,6=已下架,7=流拍
                    $end_time = time() + $auction['end_s'];
                    Db::name('auction')->where('id', '=', $id)->update(['updatetime' => time(), 'status' => '3', 'end_time' => $end_time, 'start_time' => time()]);

                    $queue = \Imi\Queue\Facade\Queue::getQueue('auction');
                    $message = new \Imi\Queue\Model\Message;
                    //发布对列
                    $message->setMessage(json_encode(['type' => 'auction_finish3', 'auction' => $auction, 'from' => '判断报名开始人数'], JSON_UNESCAPED_UNICODE));
                    var_dump('升价拍-人数-报名已满,' . $auction['end_s'] . '秒后结束');
                    $queue->push($message, (float)$auction['end_s']);


                    //推送开始拍卖
                    //推送到拍卖群组里面信息
                    $auction_start_data = ['auction_id' => $id, 'end_date' => date('Y-m-d H:i:s', $end_time), 'type_status' => $auction['type_status']];
                    $ToGroup_data = $this->ws_success('开始拍卖', $auction_start_data, 'auction_start');
                    \Imi\Server\Server::sendToGroup('auction_' . $id, $ToGroup_data, 'main');
                    \Imi\Server\Server::sendToGroup(WS_拍卖列表, $ToGroup_data, 'main'); //给拍卖群列表发送数据

                }
            }


            //推送开始拍卖
            //推送到拍卖群组里面信息
            if ($auction['start_status'] == 'number') {
                $拍卖报名信息WS = ['auction_id' => $id, 'start_status' => $auction['start_status'], 'number_num' => $count, 'type_status' => $auction['type_status']];
            } else {
                $拍卖报名信息WS = ['auction_id' => $id, 'start_status' => $auction['start_status'], 'type_status' => $auction['type_status']];
            }

            $ToGroup_data = $this->ws_success('拍卖报名', $拍卖报名信息WS, 'auction_enroll');
            \Imi\Server\Server::sendToGroup('auction_' . $id, $ToGroup_data, 'main');
            \Imi\Server\Server::sendToGroup(WS_拍卖列表, $ToGroup_data, 'main'); //给拍卖群列表发送数据

            return $this->success('报名成功');
        } else {
            return $this->error('该拍卖不能报名', '', CODE_该拍卖不能报名);
        }
    }

    /**
     * 升价拍出价
     *
     * @param int $id 拍卖id
     * @param int $plus_price 倍数
     * @param int $goods_sku_price_id 商品规格
     * @param float $price 出价格
     * @Action
     * @return void
     */
    public function offer3(?int $id, ?int $goods_sku_price_id = null, ?float $plus_price, ?float $price)
    {

        // var_dump($this->auth->user()->id);
        $_当前拍卖缓存_ = 'auction_' . (string)$id;

        $_第一名缓存_ = 'auction_first_user_id' . (string)$id;
        $_当前价格缓存_ = 'auction_price_' . (string)$id;

        $auction = Cache::get('redis', $_当前拍卖缓存_);
        if (!$auction) {
            $auction = $this->getAuctionData($id);
            if (!$auction) {
                return $this->error('没有该活动', $id, CODE_拍卖活动不存在);
            }
            Cache::set('redis', $_当前拍卖缓存_, $auction, 1);
        }

        if ($auction['type_status'] != '3') {
            return $this->error('接口错误');
        }


        $price = $plus_price * $auction['plus_price'] + $auction['start_price'];

        if (($price + $auction['plus_price']) > $auction['max_price']) {
            return $this->error('超过限高价格');
        }

        if (Cache::has('redis', $_当前价格缓存_)) {
            $_当前价格_ = Cache::get('redis', $_当前价格缓存_);
            if ($_当前价格_ == $price) {
                return $this->error('该价格已存在');
            }
        }


        $验证这个规格 = $this->验证拍卖是否有这个规格($auction,  $goods_sku_price_id);
        if ($验证这个规格 != 'ok') {
            return $this->error($验证这个规格);
        }



        switch ($auction['type_status']) {
            case '1':
                $拍卖类型 = '贝壳竞拍';
                break;
            case '2':
                $拍卖类型 = '降价拍';
                break;
            case '3':
                $拍卖类型 = '升价拍';
                break;
            case '4':
                $拍卖类型 = '暗拍(降价拍)';
                break;
            case '5':
                $拍卖类型 = '暗拍(升价拍)';
                break;
            default:
                # code...
                break;
        }
        if (!$this->GetUserSetmod($this->auth->user()->id, $this->auth->user()->set_id, MOD_升价拍)) {
            return $this->error('该等级还不支持' . $拍卖类型, $this->auth->user()->set_id);
        }



        //限高价判断
        if ($auction['max_price'] > 0 && $price > $auction['max_price']) {
            return $this->error('超过限高价', $auction['max_price'], CODE_超过限高价);
        }

        //判断活动开始没有
        if ($auction['status'] != '3') {
            return $this->error('非进行中', '', CODE_该拍卖非进行中);
        }



        if ($auction['end_time'] < time()) {
            return $this->error('活动结束', '', CODE_该拍卖活动结束);
        }

        //最后3分钟
        if (($auction['end_time'] - config('auction_final_time')) < time()) {
            $结束时间戳 = time() + config('auction_final_time');
            //重新计时
            Db::name('auction')->where('id', '=', $id)->update(['end_time' => $结束时间戳]);
            // 修改最终时间
            //从现在加时间
            //修改队列结束时间


            //推送到拍卖群组里面信息
            $auction_update_end_time_data = ['auction_final_time' => config('auction_final_time'), 'end_date' => date('Y-m-d H:i:s', $结束时间戳), 'id' => $this->auth->user()->id, 'type_status' => $auction['type_status']];
            $ToGroup_data = $this->ws_success('更新结束时间', $auction_update_end_time_data, 'auction_update_end_time');
            \Imi\Server\Server::sendToGroup('auction_' . $id, $ToGroup_data, 'main');
            \Imi\Server\Server::sendToGroup(WS_拍卖列表, $ToGroup_data, 'main'); //给拍卖群列表发送数据


            //活动结束
            $queue2 = \Imi\Queue\Facade\Queue::getQueue('auction');
            $message2 = new \Imi\Queue\Model\Message;
            //发布对列
            $message2->setMessage(json_encode(['type' => 'auction_finish' . $auction['type_status'], 'auction' => $auction, 'end_time' => $结束时间戳, 'from' => '最后三分钟'], JSON_UNESCAPED_UNICODE));
            $queue2->push($message2, (float)config('auction_final_time'));
        }




        $user_id = $this->auth->user()->id;

        //判断报名
        $_报名状态缓存_ = 'auction_enroll_' . (string)$id . '_user_id' . (string)$user_id;
        $_报名状态_ = Cache::get('redis', $_报名状态缓存_);
        if (!$_报名状态_) {
            $_报名状态存在_ = Cache::has('redis', $_报名状态缓存_);
            if (!$_报名状态存在_) {
                $data['user_id'] = $user_id;
                $data['auction_id'] = $id;
                $_报名状态res_ = Db::name('auction_enroll')->whereEx($data)->find();
                if ($_报名状态res_) {
                    Cache::set('redis', $_报名状态缓存_, true);
                    $_报名状态_ = true;
                } else {
                    Cache::set('redis', $_报名状态缓存_, false);
                    $_报名状态_ = false;
                }
            }
        }











        if (!Cache::has('redis', $_第一名缓存_)) {
            //第一次报名用户减少库存  

            $data2['auction_id'] = $id;
            $_报名_ = Db::name('auction_enroll')->whereEx($data2)->find();
            if (!$_报名_) {
                // $goods_sku_price_arr = explode(',', $auction['goods_sku_price_ids']);
                // //            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!如果库存没有了,就不能进行了
                // foreach ($goods_sku_price_arr as $key => $sku_id) {
                //     $this->DecGoodsStock($sku_id, 1, '出价' . $拍卖类型 . '活动减少库存', $id);
                // }
                $this->冻结拍卖全部库存($auction, '出价' . $拍卖类型 . '活动减少库存');
            }
        }


        //判断用户出价的价格是否最高
        //缓存读当前价格判断  如果最高修改缓存 加入数据库  否则直接返回出价失败
        if (Cache::has('redis', $_当前价格缓存_)) {
            $_当前价格_ = Cache::get('redis', $_当前价格缓存_);
        } else {
            $_当前价格_ = (float)$auction['start_price'];
        }


        if ($_当前价格_ >= $price) {
            return $this->error('不能低于当前拍卖价', $_当前价格_, CODE_低于当前拍卖价);
        }



        switch ($auction['type_status']) {
            case '1':
                $拍卖类型 = '贝壳竞拍';
                break;
            case '2':
                $拍卖类型 = '降价拍';
                break;
            case '3':
                $拍卖类型 = '升价拍';
                break;
            case '4':
                $拍卖类型 = '暗拍(降价拍)';
                break;
            case '5':
                $拍卖类型 = '暗拍(升价拍)';
                break;
            default:
                # code...
                break;
        }


        //判断用户保证金 够修改价格  扣除保证金 加入报名

        if ($this->auth->surety() < $auction['buyer_surety']) {
            return $this->error('保证金不足', '', CODE_保证金不足);
        }






        $_第一名用户id_ = Cache::get('redis', $_第一名缓存_);
        if ($_第一名用户id_) {
            if ($_第一名用户id_ != $user_id) {
                //修改领先人
                $this->UpdateFirst($id, $user_id);
            } else {
                return $this->error('不能出价超越自己');
            }
        } else {
            $this->UpdateFirst($id, $user_id);
        }

        Cache::set('redis', $_当前价格缓存_, $price);   //设置当前最高价格
        Cache::set('redis', $_第一名缓存_, $user_id);   //设置第一名用户


        //插入出价

        $data['auction_id'] = $id;
        $data['sort'] = Db::name('auction_offer')->where('auction_id', '=', $id)->count() + 1;

        //推送到拍卖群组里面信息
        $user = ['nickname' => $this->auth->user()->nickname, 'avatar' => $this->auth->user()->avatar, 'id' => $this->auth->user()->id];
        $ToGroup_data = $this->ws_success('出价', ['price' => $price, 'auction_id' => $id, 'user' => $user, 'enroll_status' => $_报名状态_ ? '2' : '1', 'count' => Db::name('auction_offer')->where('auction_id', '=', $id)->count() + 1, 'sort' => $data['sort'], 'date' => date('m.d H:i:s'), 'type_status' => $auction['type_status']], 'auction_offer');
        \Imi\Server\Server::sendToGroup('auction_' . $id, $ToGroup_data, 'main');
        \Imi\Server\Server::sendToGroup(WS_拍卖列表, $ToGroup_data, 'main'); //给拍卖群列表发送数据











        $data['user_id'] = $user_id;
        $data['price'] = $price;
        $data['goods_sku_price_id'] = $goods_sku_price_id;
        $data['time'] = $this->time();
        $data['type_status'] = $auction['type_status'];
        $data['enroll_status'] = $_报名状态_ ? '2' : '1';
        $data['status'] = '1';

        $data['id'] =  Db::name('auction_offer')->insert($data)->getLastInsertId();
        $this->DecUserSurety($user_id, $auction['buyer_surety'], $拍卖类型 . $id . '出价', $拍卖类型, $data['id']); //减去用户保证金
        $this->IncUserFreeze($user_id, 'surety', $auction['buyer_surety'], 'auction3_surety', $data['id'], $拍卖类型 . $id . '出价', null, $auction['id']); //冻结保证金

        //加入对列 修改在此时间之后且 此id以后的全出局,解冻保证金

        $queue = \Imi\Queue\Facade\Queue::getQueue('auction');
        $message = new \Imi\Queue\Model\Message;
        //发布对列
        $message->setMessage(json_encode(['type' => 'auction_out' . $auction['type_status'], 'data' => ['id' => $data['id']], 'auction' => $auction], JSON_UNESCAPED_UNICODE));
        $queue->push($message);

        Db::name('auction')->where('id', '=', $auction['id'])->update(['now_price' => $price]);

        //判断限高价 如果达到限高价就结束
        if ($auction['max_price'] > 0) {
            if (($price + $auction['plus_price']) == $auction['max_price']) {
                var_dump($auction['id'] . '到达限高价格');
                Db::name('auction')->where('id', '=', $auction['id'])->update(['max_price_status' => '2']); //修改最高限高价

                //活动结束
                $queue2 = \Imi\Queue\Facade\Queue::getQueue('auction');
                $message2 = new \Imi\Queue\Model\Message;
                //发布对列
                $message2->setMessage(json_encode(['type' => 'auction_finish' . $auction['type_status'], 'auction' => $auction], JSON_UNESCAPED_UNICODE));
                $queue2->push($message2);
            }
        }

        // Cache::set('redis', 'auction_first_user_id' . (string)$id, 'value');
        //判断是否已经出价
        // Db::name('auction_offer')->where('id','=',$id)->order('ti');
        return $this->success('出价成功');
    }

    /**
     * 获取出价记录列表
     *
     * @param int $auction_id 拍卖id
     * @param integer $page 1
     * @param integer $limit 10
     * @Action
     * @return void
     */
    public function get_offer_list($auction_id, ?int $page = 1, ?int $limit = 10)
    {
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $where['auction_id'] = $auction_id;

        $first = Db::name('auction_offer')->whereEx($where)->orderRaw('id desc')->find();
        if ($first) {
            $first['user'] = $this->GetUserData1($first['user_id']);
            $first['date'] = date('m.d H:i:s', $first['time']);
        }

        $count = Db::name('auction_offer')->whereEx($where)->count();
        $list = Db::name('auction_offer')->whereEx($where)->orderRaw('id desc')->page($page, $limit)->select()->getArray();
        foreach ($list as $key => &$val) {
            $val['user'] = $this->GetUserData1($val['user_id']);
            $val['date'] = date('m.d H:i:s', (int)($val['time'] / 10000));
        }

        return $this->success('出价列表', ['list' => $list, 'count' => $count ? $count : 0, 'first' => $first]);
    }


    /**
     * 获取用户信息头像昵称
     *
     * @param int $id 用户id
     * @return void
     */
    protected function GetUserData1($id)
    {
        return Db::name('user')->where('id', '=', $id)->fieldRaw('nickname,avatar')
            // ->cache($this->db_cache_set)
            ->find();
    }




    /**
     * 获取毫秒时间戳
     *
     * @return int
     */
    private function time()
    {
        return microtime(true) * 10000;
    }




    /**
     * 更新第一
     *
     * @param int $id
     * @param int $user_id
     * @return void
     */
    private function UpdateFirst($id, $user_id)
    {
        Db::name('auction')->where('id', '=', $id)->update(['user_id' => $user_id]);
    }


    /**
     * 改变字段
     *
     * @param array $val 
     * @return void
     */
    protected function getAuctionData($id)
    {
        $auction = Db::name('auction')->where('id', '=', $id)->find();
        return $auction;
    }





    /**
     * 改变字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeFieldList(&$val)
    {

        switch ($val['type_status']) {
            case '1':
                $拍卖类型 = '贝壳竞拍';
                break;
            case '2':
                $拍卖类型 = '降价拍';
                break;
            case '3':
                $拍卖类型 = '升价拍';

                if ($val['end_time'] < time()) {
                    if ($val['start_status'] == 'time') {
                        //结束了
                        $queue2 = \Imi\Queue\Facade\Queue::getQueue('auction');
                        $message2 = new \Imi\Queue\Model\Message;
                        //发布对列
                        $message2->setMessage(json_encode(['type' => 'auction_finish' . $val['type_status'], 'auction' => $val], JSON_UNESCAPED_UNICODE));
                        $queue2->push($message2);
                    }
                }
                $_当前价格缓存_ = 'auction_price_' . (string)$val['id'];
                if (Cache::has('redis', $_当前价格缓存_)) {
                    $_当前价格_ = Cache::get('redis', $_当前价格缓存_);
                } else {
                    $_当前价格_ = (float)$val['start_price'];
                }
                $val['now_price'] = $_当前价格_;
                break;
            case '4':
                $拍卖类型 = '暗拍(降价拍)';
                break;
            case '5':
                $拍卖类型 = '暗拍(升价拍)';
                break;
            default:
                # code...
                break;
        }
        $val['date_str'] = $this->TimeToStr($val['createtime']);
        if ($val['start_time'] > 0) {
            $val['start_date'] = date('Y-m-d H:i:s', $val['start_time']);

            if ($val['start_time'] > time())
                $val['have_start_s'] = $val['start_time'] - time();
        }

        if ($val['end_time'] > 0) {
            $val['end_date'] = date('Y-m-d H:i:s', $val['end_time']);

            if ($val['end_time'] > time())
                $val['have_end_s'] = $val['end_time'] - time();
        }



        $val['date'] = date('Y-m-d H:i:s', $val['createtime']);
        if ($val['store_id'] > 0)
            $val['store'] = $this->getStoreData2($val['store_id']);
        $val['goods'] = $this->GetGoodsShortDataById2($val['goods_id']);

        $val['goodssku_price_list'] = GoodsskuPrice::dbQuery()->whereIn('id', explode(',', $val['goods_sku_price_ids']))->fieldRaw('id,goods_sku_ids,image,price,goods_sku_text,stock')->select()->getArray();

        unset($val['minimum_price']); //卸载保留价
        return $val;
    }


    /**
     * 详情页改变字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeFieldData($val)
    {

        switch ($val['type_status']) {
            case '1':
                $拍卖类型 = '贝壳竞拍';
                break;
            case '2':
                $拍卖类型 = '降价拍';
                break;
            case '3':
                $拍卖类型 = '升价拍';

                if ($val['end_time'] < time()) {
                    if ($val['start_status'] == 'time') {
                        //结束了
                        $queue2 = \Imi\Queue\Facade\Queue::getQueue('auction');
                        $message2 = new \Imi\Queue\Model\Message;
                        //发布对列
                        $message2->setMessage(json_encode(['type' => 'auction_finish' . $val['type_status'], 'auction' => $val], JSON_UNESCAPED_UNICODE));
                        $queue2->push($message2);
                    }
                }
                $_当前价格缓存_ = 'auction_price_' . (string)$val['id'];
                if (Cache::has('redis', $_当前价格缓存_)) {
                    $_当前价格_ = Cache::get('redis', $_当前价格缓存_);
                } else {
                    $_当前价格_ = (float)$val['start_price'];
                }
                $val['now_price'] = $_当前价格_;
                break;
            case '4':
                $拍卖类型 = '暗拍(降价拍)';
                break;
            case '5':
                $拍卖类型 = '暗拍(升价拍)';
                break;
            default:
                # code...
                break;
        }
        $val['date_str'] = $this->TimeToStr($val['createtime']);
        if ($val['start_time'] > 0) {
            $val['start_date'] = date('Y-m-d H:i:s', $val['start_time']);

            if ($val['start_time'] > time())
                $val['have_start_s'] = $val['start_time'] - time();
        }

        if ($val['end_time'] > 0) {
            $val['end_date'] = date('Y-m-d H:i:s', $val['end_time']);

            if ($val['end_time'] > time())
                $val['have_end_s'] = $val['end_time'] - time();
        }



        $val['date'] = date('Y-m-d H:i:s', $val['createtime']);
        if ($val['store_id'] > 0)
            $val['store'] = $this->getStoreData3($val['store_id']);
        $val['goods'] = $this->GetGoodsShortDataById2($val['goods_id']);

        $val['goodssku_price_list'] = GoodsskuPrice::dbQuery()->whereIn('id', explode(',', $val['goods_sku_price_ids']))->fieldRaw('id,goods_sku_ids,image,price,goods_sku_text,stock')->select()->getArray();

        unset($val['minimum_price']); //卸载保留价
        return $val;
    }
}
